﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using CMS.Commons;
using CMS.Business.ViewModels;
using WebMatrix.WebData;
using System.Web.Security;

namespace CMS.Web.App_Start
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
    public class CmsAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            bool isSuccess = true;
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");
            var routeData = new RouteData();
            if (httpContext.Request.RequestContext.RouteData != null)
                routeData = httpContext.Request.RequestContext.RouteData;

            var controller = "";
            var action = "";
            if (routeData.Values.Count == 0)
                return true;
            controller = routeData.GetRequiredString("controller").ToUpper();
            action = routeData.GetRequiredString("action").ToUpper();

            var xmlValue = XmlUltil.ReadFile(httpContext.Server.MapPath("~/App_Data/RoleAuthorizeConfig.xml"));

            var list = XmlUltil.DeSerializeToObject<List<RightAccessViewModel>>(xmlValue);

            bool isAnonymous = list.Any(t => t.Controlers.Any(c => c.ToUpper() == controller) && ("*".Equals(t.Action) ? true : t.Action.ToUpper() == action) && "anonymous".Equals(t.Role));
            if (isAnonymous)
            {
                return true;
            }

            string currentUser = string.Empty;
            string rolesString = string.Empty;

            //roles
            if (currentUser != null)
            {
                if (rolesString != null)
                {
                    if (!string.IsNullOrEmpty(rolesString))
                    {
                        bool isValid = list.Any(t => t.Controlers.Any(c => c.ToUpper() == controller) && ("*".Equals(t.Action) ? true : t.Action.ToUpper() == action) && t.Role == rolesString.Trim());

                        if (isValid)
                        {
                            return isSuccess && httpContext.Request.IsAuthenticated;
                        }
                    }
                }
            }

            return false;
        }
    }
}